import Component from 'utils/js/jquery-component';
import createClass from 'utils/js/create-class';
import s from './index.css';
import loadVideos from 'utils/js/loadVideos';

export default createClass(Component, {
  __name__: 'Example',
  locals: s,

  __init__: function (el, srcs) {
    this.$wrap = this.$(el || document.body);
    this.$video = this.$(`<video class="${s.video}" muted>`);
    this.video = this.$video[0];
    this.index = 0;
    this.srcs = srcs || [];
    var me = this;
    this.video.onended = function () {
      me.index = (me.index + 1) % me.srcs.length;
      me.video.src = me.srcs[me.index];
      me.video.play();
    };
    loadVideos(this.srcs).then(function (srcs) {
      if (!srcs.length) return;
      me.video.src = srcs[me.index];
      me.$video.appendTo(me.$wrap);
      srcs.length && me.play();
    }).catch(function (e) {
      console.error(e);
    });
  },

  play: function () {
    if (!this.srcs.length) return;
    if (!this.video.paused) return;
    this.video.play();
  },

  pause: function () {
    if (!this.srcs.length) return;
    if (this.video.paused) return;
    this.video.pause();
  },
});
